package com.example.demo.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.example.demo.enums.RedisPreEnum;
import com.example.demo.common.PassToken;
import com.example.demo.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Resource
    RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String  token = request.getHeader("token");
        if (request.getHeader("Connection").equals("Upgrade")){
            return true;
        }
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod =(HandlerMethod) handler;
        Method method =handlerMethod.getMethod();
        if (method.isAnnotationPresent(PassToken.class)){
            PassToken passToken = method.getAnnotation(PassToken.class);
            if(passToken.required()){
                return true;
            }
        }
        if (token==null){
            throw new RuntimeException("无token,请重新登录");
        }
        String userId;
        try{
            userId= JWT.decode(token).getAudience().get(0);
            System.out.println(userId);
        }catch (JWTDecodeException e){
            throw new RuntimeException("token无效");
        }
        String  key = RedisPreEnum.JWT_TOKEN_PRE.getPre()+userId;
        if (!redisUtil.get(key).toString().equals(token)){
            log.info("key:"+redisUtil.get(key).toString()+"\n"+"token:"+token);
            throw  new RuntimeException("token无效");
        }
        else if (redisUtil.getExpireByKey(key)<300L){
            redisUtil.expire(key,7200L);
        }
//        User user= null;
//        System.out.println("key:"+key);
//        if (redisUtil.hashKey(key)){
//            Object o =redisUtil.get(key);
//            System.out.println(o);
//            user = JSONObject.toJavaObject((JSON)JSON.toJSON(o),User.class);
//        }
//        if (user==null){
//            throw new RuntimeException("请重新登录");
//        }
//        JWTVerifier jwtVerifier =JWT.require(Algorithm.HMAC256(user.getPassword())).build();
//        try {
//            jwtVerifier.verify(token);
//        }catch (Exception e){
//            throw new Exception("token无效");
//        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
